import { BaseService, CoolCommException } from "@cool-midway/core";
import { Provide } from "@midwayjs/core";
import { Repository } from "typeorm";
import { UserContactEntity } from "../entity/contact";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { UserInfoEntity } from "../entity/info";

@Provide()
export class UserContactService extends BaseService {

    @InjectEntityModel(UserContactEntity)
    userContactModel: Repository<UserContactEntity>

    @InjectEntityModel(UserInfoEntity)
    userInfoModel: Repository<UserInfoEntity>

    async setDefault(userId: number, contactId: number) {
        // 校验用户是否存在，使用 exist 避免加载实体
        const userExists = await this.userInfoModel.exist({ where: { id: userId } });
        if (!userExists) {
            throw new CoolCommException('用户不存在');
        }

        // 校验联系人是否存在且归属该用户
        const contact = await this.userContactModel.findOne({ where: { id: contactId, userId } });
        if (!contact) {
            throw new CoolCommException('该联系人不存在');
        }

        // 使用事务，先清空默认，再设置新的默认，保证原子性
        await this.userContactModel.manager.transaction(async manager => {
            await manager.update(UserContactEntity, { userId }, { isDefault: false });
            await manager.update(UserContactEntity, { id: contactId, userId }, { isDefault: true });
        });

        return await this.userContactModel.findOne({ where: { id: contactId, userId } });
    }

}